package com.dwjm.controller;

import java.net.URLEncoder;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.dwjm.entity.SitesCollection;
import com.dwjm.entity.User;
import com.dwjm.service.SitesCollectionService;
import com.dwjm.service.UserService;
import com.dwjm.util.EncryptUtil;

/**
 * 网站收藏表Controller层
 * 
 * @date 2016年12月29日
 * @auther luans
 */
@Controller
@RequestMapping("colctr")
public class SitesCollectionController {

	@Resource
	private SitesCollectionService sitesCollectionService;
	@Resource
	private UserService userService;

	/**
	 * 收藏操作：添加、删除
	 * 
	 * 
	 * @date 2016年12月29日
	 * @auther luans
	 */
	@RequestMapping("col")
	@ResponseBody
	public int backPwd(HttpServletRequest request,
			HttpServletResponse response, SitesCollection collection) {
		int result = 0;
		User user = new User();
		user.setUid(collection.getColUid());
		user = userService.selectByPrimaryKey(user);
		user.setPccolid(0);
		if (collection.getMarkerType() == 1) {
			// 添加收藏
			result = sitesCollectionService.insertSelective(collection);
			user.setPccolid(result);

		} else if (collection.getMarkerType() == 2) {
			// 取消收藏
			result = sitesCollectionService.deleteByPrimaryKey(collection
					.getColId());
		}
		//修改用户session和cookie中的值
		resetValue(request,response,user);
		return result;

	}

	/**
	 * 收藏操作完成后修改session和cooike中的信息
	 * 
	 * 
	 * @date 2016年12月29日
	 * @auther luans
	 */
	public void resetValue(HttpServletRequest request,
			HttpServletResponse response, User user) {
		// 添加seession
		HttpSession session = request.getSession();
		session.setAttribute("pc_user", user);// 将用户信息存入Session

		// 判断cookie是否修改
		Cookie cookiearray[] = request.getCookies();
		if (cookiearray != null) {
			for (int i = 0; i < cookiearray.length; i++) {
				if ("pc_user_cookie".equals(cookiearray[i].getName())) {
					// 存在用户cookie，重新添加
					try {
						String value = EncryptUtil.base64Encoder(user.getUid()
								+ ";" + user.getEmail() + ";" + user.getPwd()
								+ ";" + "2" + ";" + user.getPccolid());
						value = URLEncoder.encode(value, "utf-8");
						Cookie cookie1 = new Cookie("back_user_cookie", value);
						cookie1.setMaxAge(60 * 60 * 24 * 1);// 设置Cookie的有效时间为1天
						cookie1.setPath("/");// cookie有效路径是网站根目录
						response.addCookie(cookie1); // 向客户端写入
					} catch (Exception e) {
						System.out.println("收藏时，添加用户cookie问题");
					}// 用base64加密;最后加的“2”，标记是PC端用户登录
				}

			}
		}

	}

}
